package com.weixing.mall.provider.support.mq;

import com.weixing.mall.provider.service.IActivityGoodsService;
import com.weixing.mall.redis.RedisKeyConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IActivityGoodsService activityGoodsService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
        String expiredKey = serializer.deserialize(message.getBody());
        if(expiredKey.startsWith(RedisKeyConst.ORDER_PAY_END_TIME_EX_PRE)){
            int start = expiredKey.indexOf("::");
            int end = expiredKey.lastIndexOf("::");
            long orderId = Long.parseLong(expiredKey.substring(start + 2, end));
            long itemId = Long.parseLong(expiredKey.substring(end + 2));
            System.out.println(orderId + "::" + itemId);
//            activityGoodsService.cancelOrder(orderId,itemId);
        }
    }
}